package cs633.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ResourceBundle;

public class S3Mounter {
	static String userPath = "webapps/PhotoShare/images/user";
	
	public static void mount() {
		if (!System.getProperty("os.name").equals("Linux")) {
			System.out.println("Not running on a Linux server!  Can't use S3FS!");
			File userDir = new File(userPath);
			if (!userDir.exists()) {
				userDir.mkdir();
			}
			return;
		}
		
		ResourceBundle res = ResourceBundle.getBundle("resource");
		String s3keyid = res.getString("s3keyid");
		String s3key = res.getString("s3key");
		String credpath = null;
		File tempfile = null;
		try {
			tempfile = File.createTempFile("tmp", "");
			tempfile.deleteOnExit();
			FileWriter tempw = new FileWriter(tempfile);
			credpath = tempfile.getAbsolutePath();
			tempw.write(s3keyid + ":" + s3key);
			tempw.close();
		} catch (IOException error) {
			error.printStackTrace();
			System.out.println("Unable to create temp file for S3 credentials!");
			if (tempfile != null) {
				tempfile.delete();
			}
			return;
		}
		
		String commands[] =
		{
			String.format("umount %s", userPath),
			String.format("modprobe fuse"),
			String.format("mkdir -p %s", userPath),
			String.format("chmod 600 %s", credpath),
			String.format("s3fs cs633-group1 %s -o passwd_file=%s", userPath, credpath)
		};
			
		for (int i = 0; i < commands.length; i++) {
			String command = commands[i];
			try {
				Runtime.getRuntime().exec(command).waitFor();
			} catch (InterruptedException error) {
				System.out.println("Aborted S3 mount.");
			} catch (IOException error) {
				System.out.println("Error mounting S3 bucket.");
				error.printStackTrace();
			}
		}
	
		File userDir = new File(userPath);
		if (!userDir.exists()) {
			userDir.mkdir();
		}
		
		tempfile.delete();
	}
	
	public static void unmount() {
		String commands[] =
		{
			String.format("umount %s", new Object[]{userPath})
		};
		
		if (System.getProperty("os.name").equals("Linux")) {			
			for (int i = 0; i < commands.length; i++) {
				String command = commands[i];
				try {
					Runtime.getRuntime().exec(command).waitFor();
				} catch (InterruptedException error) {
					System.out.println("Aborted S3 unmount.");
				} catch (IOException error) {
					System.out.println("Error unmounting S3 bucket.");
					error.printStackTrace();
				}
			}
		}
	}
}
